import org.apache.kudu.ColumnSchema;
import org.apache.kudu.Schema;
import org.apache.kudu.Type;
import org.apache.kudu.client.CreateTableOptions;
import org.apache.kudu.client.KuduClient;
import org.apache.kudu.client.KuduException;

import java.util.ArrayList;

//Kudu API创建表
public class CreateTableDemo {
    public static void main(String[] args) {
        //指定表连接到的master节点主机名
        String masterAddress = "linux121";
        //获取客户端
        KuduClient.KuduClientBuilder builder = new KuduClient.KuduClientBuilder(masterAddress);
        KuduClient client = builder.build();

        String tableName = "student";
        //student表的列名： id int (pkey) , name string

        //定义schema，指定每一列的信息，每个字段必须显示说明是否为主键
        ArrayList<ColumnSchema> colSchemas = new ArrayList<>();
        //key(boolean)，传入true代表字段是主键
        ColumnSchema id = new ColumnSchema.ColumnSchemaBuilder("id", Type.INT32).key(true).build();
        ColumnSchema name = new ColumnSchema.ColumnSchemaBuilder("name", Type.STRING).key(false).build();
        colSchemas.add(id);
        colSchemas.add(name);
        Schema schema = new Schema(colSchemas);

        //指定副本数量、分区策略和数量
        CreateTableOptions options = new CreateTableOptions();
        //副本数量为1
        options.setNumReplicas(1);
        ArrayList<String> colRule = new ArrayList<>();
        colRule.add("id");
        options.addHashPartitions(colRule, 3);

        try {
            client.createTable(tableName, schema, options);
        }catch (KuduException e){
            e.printStackTrace();
        }finally {
            try {
                client.close();
            }catch (KuduException e){
                e.printStackTrace();
            }
        }
    }
}
